#include <sys/types.h>
#include <sys/socket.h>
#include <unistd.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <iostream>
#include"Thread.hpp"
#include"InetAddr.hpp"
using namespace std;
int InitClient()
{
    int sockfd = ::socket(AF_INET, SOCK_DGRAM, 0);
    if (sockfd < 0)
    {
        cout << "create socket error"<< endl;
        exit(1);
    }
    return sockfd;
}
void Send(int sockfd,string serverip,uint16_t serverport,const string& name)
{
    struct sockaddr_in server;
    server.sin_family = AF_INET;
    server.sin_addr.s_addr = inet_addr(serverip.c_str());
    server.sin_port = serverport;
     while (1)
    {
        string msg;
        std::getline(std::cin, msg);
        int n = sendto(sockfd, msg.c_str(), msg.size(), 0, (struct sockaddr *)&server, sizeof(server));
        if (n <= 0)
        {
            break;
        }
    }
}
void Receive(int sockfd,const string& name)
{
    while(1)
    {
        char buf[512];
        struct sockaddr_in usr;
        socklen_t len;
        int m = recvfrom(sockfd, buf, sizeof(buf) - 1, 0, (struct sockaddr *)&usr, &len);
        if (m > 0)
        {
            buf[m] = 0;
            cout << endl;
            cout << buf << endl;
        }
        else
        { 
            break;
        }
    }
}
int main(int argc, char *argv[])
{
     if (argc != 3)
    {
        cerr << "usage:" << argv[0] << "error" << endl;
        exit(0);
    }
    string serverip = argv[1];
    uint16_t serverport = htons(stoi(argv[2]));
    int sockfd = InitClient();
    tfunc_t rvf = bind(&Receive, sockfd, placeholders::_1);
    tfunc_t sdf = bind(&Send, sockfd, serverip, serverport, placeholders::_1);
    Thread rv("receiver-thread", rvf);
    Thread sd("send-thread",sdf);
    rv.Start();
    sd.Start();
    rv.Join();
    sd.Join();
    // 客户端一定要知道服务器的ip和端口
    // 客户端的端口号一般不由用户自己设定，而是OS随机选择，服务器一定要自己设定
    // 客户端首次向服务器发送数据的时候，OS会自动给client绑定
   
    ::close(sockfd);
}